package com.imay.live.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;

import com.imay.live.R;
import com.imay.live.manager.MessageManager;

import java.io.File;
import java.io.IOException;

/**
 * Created by nick on 2017/7/25.
 * 音乐播放工具类
 */

public class SimpleMediaPlayerUtil {

    private MediaPlayer mediaPlayer;

    private static class MessageManagerHolder {
        private static final SimpleMediaPlayerUtil INSTANCE = new SimpleMediaPlayerUtil();
    }

    public static final SimpleMediaPlayerUtil getInstance() {
        return SimpleMediaPlayerUtil.MessageManagerHolder.INSTANCE;
    }

    private SimpleMediaPlayerUtil() {

    }

    public boolean init(Context context,File file){
        mediaPlayer=MediaPlayer.create(context,  Uri.parse(file.getPath()));
        if (mediaPlayer == null){
            ToastUtil.show(context, R.string.music_play_fial);
            file.delete();
            return false;
        }
        mediaPlayer.setLooping(true);
        try {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer=MediaPlayer.create(context,  Uri.parse(file.getPath()));
                return true;
//
            }

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(context, R.string.music_play_fial);
            file.delete();
            return false;
        }

        return true;

    }

    public void play() {
        if (mediaPlayer!=null){
            mediaPlayer.start();
        }

    }

    public void pause() {
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    public void stop() {
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            mediaPlayer.reset();
        }
    }

    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    public boolean isPlaying() {
        if (mediaPlayer!=null&&mediaPlayer != null) {
           return mediaPlayer.isPlaying();
        }
        return false;
    }


}
